import React from "react";
import {designPage} from "../../src";
import Schema, {Rules} from 'async-validator'

export const AsyncValidatorDemo = designPage(() => {

    const test = () => {
        const rules: Rules = {
            userName: {
                type: 'string',
                required: true,
                message: '请输入名称',
            },
            name: {
                type: 'string',
                required: true,
                validator: (rule, value) => value === 'muji',
            },
            age: {
                type: 'number',
                asyncValidator: (rule, value) => {
                    return new Promise((resolve, reject) => {
                        if (value < 18) {
                            reject('太年轻了');  // reject with error message
                        } else {
                            resolve();
                        }
                    });
                },
            },
        };
        const validator = new Schema(rules);

        // PROMISE USAGE
        validator.validate({name: 'muji', age: 16}).then(() => {
            // validation passed or without error message
            console.log('校验通过')
        }).catch(({errors, fields}) => {
            console.log({errors, fields})
            console.error('校验失败')
        });
    }


    return () => <>
        <button onClick={() => test()}>test</button>
    </>
})